﻿CREATE TRIGGER [tr_TrackerRequest_VIN]
ON [dbo].[t_TrackerRequest] 
FOR UPDATE
AS

IF @@ROWCOUNT = 0 RETURN

IF NOT UPDATE (VIN) RETURN

DECLARE @TrackerID varchar(50)
SELECT @TrackerID = tc.TrackerID FROM t_Tracker_Car tc INNER JOIN inserted i ON tc.TrackerRequestID = i.ID
IF @TrackerID > '' BEGIN
	ROLLBACK TRAN
	RAISERROR('Can''t change VIN when tracker[%s] is installed.',16,1,@TrackerID)
	RETURN
END

DECLARE @TrackerRequestID int,@VIN varchar(17),@Type sysname
SELECT @TrackerRequestID = dbo.TrackerRequest_PendingInstall(ID,VIN),@VIN = VIN,@Type = 'Installation' FROM inserted
IF @TrackerRequestID IS NULL
	SELECT @TrackerRequestID = dbo.TrackerRequest_PendingRemove(ID,VIN),@VIN = VIN,@Type = 'Removal' FROM inserted
IF @TrackerRequestID > 0 BEGIN
	ROLLBACK TRAN
	DECLARE @ShowTrackerRequest nvarchar(1024) SET @ShowTrackerRequest = dbo.ShowTrackerRequest(@TrackerRequestID)
	RAISERROR('Pending %s Request[%d] is already assign to VIN [%s].%s',16,1,@Type,@TrackerRequestID,@VIN,@ShowTrackerRequest)
	RETURN
END

IF (SELECT COUNT(*) FROM inserted) <> 1 RETURN
-- =========== Dealer ID =============
DECLARE @DealerID int
SELECT @DealerID = li.DealerID FROM v_LoanInfo_10 li INNER JOIN inserted i ON li.VIN = i.VIN

IF @DealerID IS NULL
	SELECT TOP 1 @DealerID = tr.DealerID FROM t_TrackerRequest tr
	INNER JOIN inserted i ON tr.VIN = i.VIN
	WHERE tr.DealerID > 0
	ORDER BY tr.StatusDate DESC

UPDATE t_TrackerRequest SET DealerID = @DealerID WHERE ID = (SELECT ID FROM inserted WHERE VIN > '') AND NOT @DealerID IS NULL

--IF dbo.RequestStatus_Attr_LockInstaller(DEFAULT,(SELECT StatusID FROM inserted)) = 0 RETURN

--DECLARE @Status sysname SELECT @Status = t_Menu.MenuName FROM inserted i INNER JOIN t_Menu ON i.StatusID = t_Menu.MenuID
--RAISERROR('Can''t change Installer while in [%s] status.',16,1,@Status)




